import java.sql.*;

public class JDBCUtil {
    //数据库的用户名
    private final String USER = "root";
    //数据库密码
    private final String PASSWORD = "123456";
    //数据库的访问链接
    private static final String URL = "jdbc:mysql://localhost:3306/scheduling";//scheduling为数据库名
    //数据库的驱动
    private final String DRIVER = "com.mysql.cj.jdbc.Driver";
    //获取JDBCManager 的对象
    private static JDBCUtil instance;
    //数据库的执行空间
    private PreparedStatement statement;
    //数据库的连接
    private Connection connection;

    /**
     * 构造方法私有化
     */
    private JDBCUtil() {
        try {
            Class.forName(DRIVER);
//            System.out.println("注册MySQL驱动成功");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 单例模式构建访问数据库的访问对象
     *
     * @return
     */
    public static JDBCUtil getInstance() {
        if (instance == null) {
            instance = new JDBCUtil();
        }
        return instance;
    }

    /**
     * 获得数据库的连接
     *
     * @return
     */
    public Connection getConnection() throws SQLException {
        connection = DriverManager.getConnection(URL, USER, PASSWORD);
        return connection;
    }

    /**
     * 执行静态的SQL语句
     *
     * @param sql
     * @return 返回一个整型，整型值为数据库受影响的行数
     * @throws SQLException
     */
    public int executeSQLByStatement(String sql) throws SQLException {
        statement = connection.prepareStatement(sql);
        return statement.executeUpdate(sql);
    }

    /**
     * 执行DML语句，例如删除，插入，修改
     * insert into student()
     *
     * @param sql
     * @param columnName 列名称
     * @return
     * @throws SQLException
     */
    public int executeSQLBYStatement(String sql, String[] columnName) throws SQLException {
        statement = connection.prepareStatement(sql);
        return statement.executeUpdate(sql, columnName);
    }

    /**
     * 查询返回的结果，可能包含一个或者多个结果
     * 返回值                     参数
     * 方法  int        executeUpdate​(String sql, int[] columnIndexes)
     *
     * @param sql
     * @return
     * @throws SQLException
     */

    public ResultSet executeQuetyBYStatement(String sql) throws SQLException {
        statement = connection.prepareStatement(sql);
        return statement.executeQuery(sql);
    }

    /**
     * 将关闭流放入方法中减少代码重复量
     */
    public void closeAll() {
        try {
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
